//
//  LCMineViewController.swift
//  mggz
//
//  Created by 匀视网Mac on 2018/1/4.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Moya
import ObjectMapper
class LCMineViewController: UIViewController {
     var selectedProject : LCProjectListModel?
    fileprivate var mineInfoModel:LCMineInfoModel?
    @IBOutlet weak var tableView: UITableView!
    let titleArray  = [["","基本设置","项目民工"],["公司管理","在职民工","民工入职","身份(账号)切换","法律条款和隐私政策"]]
    let titleImgArray = [["","baseSet","projectWorker"],["companyManager","projectWorker","AddWorker","",""]]
    let headerArray = ["项目","公司"]
    let headerColor = [UIColor.yellow,UIColor.LightGreen]
    fileprivate lazy var tableHeaderView:LCMineHeaderView = {
        let tableHeaderView = LCMineHeaderView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 150))
        tableHeaderView.clickDelegete = {
            var vc = MessageController(nibName: "MessageController", bundle: nil)
            self.navigationController?.pushViewController(vc, animated: true)
        }
        return tableHeaderView
    }()
    
    lazy var exitVc:UIAlertController = {
        var cancelBtn = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (action) in
            
        })
        var submitBtn = UIAlertAction(title: "确定", style: UIAlertActionStyle.default, handler: { (action) in
            
            self.logoffClient()
        })
        var alertView = UIAlertController(title: "提示", message: "确定要切换账号吗？", preferredStyle: UIAlertControllerStyle.alert)
        alertView.addAction(cancelBtn)
        alertView.addAction(submitBtn)
        return alertView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //edgesForExtendedLayout = UIRectEdge.all
        
        //self.navigationController?.navigationBar.isTranslucent = false
       // self.navigationController?.navigationBar.isHidden = true
        self.view.backgroundColor = UIColor.white
        self.selectedProject?.ProjectName = "暂无项目"
        self.setupHeaderView()
        self.tableView.backgroundColor = UIColor.init(red: 89/255.0, green: 115/255.0, blue: 144/255.0, alpha: 1)
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorStyle = .none
        self.tableView.register(UINib.init(nibName: "CurrentProjectCell", bundle: nil), forCellReuseIdentifier: "current")
        self.tableView.register(UINib.init(nibName: "LCMineCell", bundle: nil), forCellReuseIdentifier: "mine")
        self.tableView.register(UINib.init(nibName: "MenuBottomCell", bundle: nil), forCellReuseIdentifier: "bottom")
        self.getEployeeInformation()
        self.addNotificationObserve()
        
    }
    fileprivate func getEployeeInformation(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
      MWApiMainManager.request(.GetEmployeeInformation(AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                print(jsonString)
                guard let message : String = jsonString["Msg"] as? String else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    QWTextonlyHud(message, target: self.view)
                    return
                }
                guard let resultDic = jsonString["Result"] as? [String: AnyObject] else{
                    return
                }
                print(jsonString)
                let textImg = "https://www.baidu.com/img/bd_logo1.png"
                //let imgurl = ImageUrlPrefix + (self.mineInfoModel?.Portrait ?? "")
                self.mineInfoModel = Mapper<LCMineInfoModel>().map(JSONObject: resultDic)
                let imgurl = (ImageUrlPrefix + (self.mineInfoModel?.Portrait ?? "")).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
                
                
                self.tableHeaderView.headerView.kf.setImage(with: URL.init(string: imgurl!), placeholder: UIImage.init(named: "scene_touxiang"), options: nil, progressBlock: nil, completionHandler: nil)
                
                self.tableHeaderView.companyName.text = self.mineInfoModel?.CompanyName ?? ""
                
                let managerName = self.mineInfoModel?.Name ?? ""
                self.tableHeaderView.managerName.text = "管理员:" + managerName
                
            }
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.mm_drawerController.openDrawerGestureModeMask = .all
        self.mm_drawerController.closeDrawerGestureModeMask = .all
        self.navigationController?.isNavigationBarHidden = true
        self.mm_drawerController.maximumLeftDrawerWidth = SCREEN_WIDTH * 0.8
        
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.mm_drawerController.closeDrawerGestureModeMask = .custom
        self.mm_drawerController.openDrawerGestureModeMask = .custom
        self.navigationController?.isNavigationBarHidden = false
        self.mm_drawerController.maximumLeftDrawerWidth = SCREEN_WIDTH
        
    }
    private func addNotificationObserve(){
        let noficationName = Notification.Name.init(LCMainProjectNotification)
        
        NotificationCenter.default.addObserver(self, selector: #selector(getMWLocationData(notification:)), name: noficationName, object: nil)
    }
    
    @objc func getMWLocationData(notification:Notification) {
        let userInfo = notification.userInfo as! [String:AnyObject]
        self.selectedProject = userInfo["project"] as? LCProjectListModel
        self.tableView.reloadData()
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //关闭侧滑layout通知
    func sendCloseMenuNotifition(_ operate:NormalClick){
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: DrawLayoutNotification), object: operate)
    }
    
    
    private func setupHeaderView(){
//        let headerView = UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 180))
//
//        let personView = UIImageView.init(image: UIImage.init(named: "mine_person"))
//        personView.frame = CGRect(x: (0.8*SCREEN_WIDTH-100)/2, y: 20, width: 100, height: 100)
//        headerView.backgroundColor = UIColor.init(red: 89/255.0, green: 115/255.0, blue: 144/255.0, alpha: 1)
//        headerView.addSubview(personView)
//
//        let companyName = UILabel.init(frame: CGRect(x: 20, y: 130, width: 0.8*SCREEN_WIDTH-40, height: 21))
//        companyName.text = self.selectedProject?.ProjectName
//        companyName.textAlignment = .center
//        headerView.addSubview(companyName)
//
//        let manager = UILabel.init(frame: CGRect(x: 20, y: 161, width: 0.8*SCREEN_WIDTH-40, height: 21))
//        manager.text = "管理员:"+"姜正荣"
//        manager.textColor = UIColor.white
//        manager.textAlignment = .center
//        headerView.addSubview(manager)
        
        self.tableView.tableHeaderView = self.tableHeaderView
        self.tableHeaderView.backgroundColor = UIColor.init(red: 89/255.0, green: 115/255.0, blue: 144/255.0, alpha: 1)
    }
    
    //注销客户端
    func logoffClient(){
        QWTextWithStatusHud("正在注销...", target: self.view)
        var params:[String:Any] = ["productType":"民工端","clientID":JPUSHService.registrationID()]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .LogoffClient, params: &params, type: LogoffModel.self, success: { (bean, _) in
            QWHudDiss(self.view)
            
            
        }) { (error) in
            QWHudDiss(self.view)
            switch error{
            case .StateFail(let data):
                guard var str = data as? String else{
                    QWTextonlyHud("注销失败，请重试", target: self.view)
                    return
                }
                if str == "OK"{
                    (UIApplication.shared.delegate as! AppDelegate).setTags(nil)
                    LoginType = -1
                    let rootVC = LoginViewController()
                    UIApplication.shared.delegate?.window!?.rootViewController = rootVC
                    UIApplication.shared.delegate?.window!?.makeKeyAndVisible()
                }else{
                    QWTextonlyHud("注销失败，请重试", target: self.view)
                }
                break
            case .HTTPERROR:
                QWTextonlyHud("网络异常", target: self.view)
                break
            case .DATAERROR:
                //QWTextonlyHud("失败，请重试", target: self.view)
                break
            case .DATAFAIL:
                //QWTextonlyHud("注销失败，请重试", target: self.view)
                break
            }
        }
    }
  
    
}
extension LCMineViewController : UITableViewDataSource,UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titleArray[section].count
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return titleArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 && indexPath.row == 0{
            let cell : CurrentProjectCell = tableView.dequeueReusableCell(withIdentifier: "current") as! CurrentProjectCell
            cell.backgroundColor = UIColor.init(red: 89/255.0, green: 115/255.0, blue: 144/255.0, alpha: 1)
            cell.contentView.backgroundColor = UIColor.init(red: 89/255.0, green: 115/255.0, blue: 144/255.0, alpha: 1)
            
            if selectedProject?.ProjectName == "暂无项目" || selectedProject?.OrderNo == nil {
                cell.titleLabel.isHidden = true
                cell.projectName.isHidden = true
                cell.codeLabel.isHidden = true
                cell.noProject.isHidden = false
            }else{
                cell.titleLabel.isHidden = false
                cell.projectName.isHidden = false
                cell.codeLabel.isHidden = false
                cell.noProject.isHidden = true
                cell.projectName.text = selectedProject?.ProjectName
                cell.codeLabel.text = "编号:"+(selectedProject?.OrderNo)!
            }
            cell.selectionStyle = .none
            return cell

        }else if indexPath.section == 1 && indexPath.row == (self.titleArray[1].count - 1){
            let cell = tableView.dequeueReusableCell(withIdentifier:"bottom") as! MenuBottomCell
            cell.selectionStyle = .none
            //cell.titleview.text = self.titleArray[1][indexPath.row] ?? ""
            cell.titleview.attributedText = NSMutableAttributedString(string: self.titleArray[1][indexPath.row] ?? "", attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 15)])
            cell.backgroundColor = UIColor.init(red: 89/255.0, green: 115/255.0, blue: 144/255.0, alpha: 1)
            return cell
            
        }else{
            let cell : LCMineCell = tableView.dequeueReusableCell(withIdentifier: "mine") as! LCMineCell
             cell.titleLabel.text = titleArray[indexPath.section][indexPath.row]
            cell.backgroundColor = UIColor.init(red: 89/255.0, green: 115/255.0, blue: 144/255.0, alpha: 1)
            cell.contentView.backgroundColor = UIColor.init(red: 89/255.0, green: 115/255.0, blue: 144/255.0, alpha: 1)
            cell.selectionStyle = .none
            if titleImgArray[indexPath.section][indexPath.row] != ""{
                cell.titleImg.image = UIImage(named: titleImgArray[indexPath.section][indexPath.row])
            }else{
                cell.leftContent.constant = 25
            }
            
            return cell
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 && indexPath.row==0{
            return 99
        }
        return 45
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 35;
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 35))
        headerView.backgroundColor = UIColor.init(red: 89/255.0, green: 115/255.0, blue: 144/255.0, alpha: 1)
        //let iconView = UIImageView.init(image: UIImage.init(named: "Icon_借款资料认证"))
        let tagView = UIView(frame: CGRect(x: 25, y: 15, width: 15, height: 15))
        tagView.backgroundColor = self.headerColor[section]
        headerView.addSubview(tagView)
        
        /*iconView.frame = CGRect(x: 25, y: 10, width: 25, height: 25)
        headerView.addSubview(iconView)*/
        let titleLabel = UILabel.init(frame: CGRect(x: 50, y: 12, width: 100, height: 21))
        titleLabel.text = headerArray[section]
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        headerView.addSubview(titleLabel)
        
        return headerView
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 && indexPath.row==0{
            /*let projectSelect = LCProjectSelectViewController(nibName: "LCProjectSelectViewController", bundle: nil)
            
            self.navigationController?.pushViewController(projectSelect, animated: true)*/
            //self.sendCloseMenuNotifition(_ operate:NormalClick)
        }
        
        if indexPath.section == 0 && indexPath.row == 1 {
            /*let operate:NormalClick = {
                
            }
            self.sendCloseMenuNotifition(operate)*/
            
            let basicView = LCBasicSetViewController(nibName: "LCBasicSetViewController", bundle: nil)
            basicView.currentProject = self.selectedProject
            self.navigationController?.pushViewController(basicView, animated: true)
        }
        if indexPath.section == 0 && indexPath.row == 2{
         let wngAdd = WNGAddViewController(nibName: "WNGAddViewController", bundle: nil)
            wngAdd.currentProject = selectedProject;
            self.navigationController?.pushViewController(wngAdd, animated: true)
        }
        if indexPath.section == 1 && indexPath.row == 0{
            let companyManager = LCCompanyManagerViewController(nibName: "LCCompanyManagerViewController", bundle: nil)
            companyManager.currentProject = selectedProject
        self.navigationController?.pushViewController(companyManager, animated: true)
        }
        if indexPath.section == 1 && indexPath.row == 1{
            let workerOnJob = WorkerOnJobViewController(nibName: "WorkerOnJobViewController", bundle: nil)
            self.navigationController?.pushViewController(workerOnJob, animated: true)
        }
        if indexPath.section == 1 && indexPath.row == 2{
           let workEntry = EntryFirstpageViewController(nibName: "EntryFirstpageViewController", bundle: nil)
            workEntry.currentProject = self.selectedProject
            self.navigationController?.pushViewController(workEntry, animated: true)
        }
        if indexPath.section == 1 && indexPath.row == 3 {
            print("退出")
            /*var cancelBtn = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (action) in
                
            })
            var submitBtn = UIAlertAction(title: "确定", style: UIAlertActionStyle.default, handler: { (action) in
                
                self.logoffClient()
            })
            var alertView = UIAlertController(title: "提示", message: "确定要切换账号吗？", preferredStyle: UIAlertControllerStyle.alert)
            alertView.addAction(cancelBtn)
            alertView.addAction(submitBtn)*/
            self.present(self.exitVc, animated: true, completion: nil)
        }
        
        if indexPath.section == 1 && indexPath.row == 4 {
            var vc = CompanyAboutController(nibName: "CompanyAboutController", bundle: nil)
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        
    }
}















